# -*- coding: utf-8 -*-
"""
发送数据工具模块
"""

import requests
import logging
import asyncio
import aiohttp
from dataUtils import get_upload_data, byte_to_str, word_to_str
from imgUtils import base64_to_pixel_array, base64_to_pixel_array_async
from config import epd_ind, ip_address

async def send_command_async(cmd):
    """
    异步发送基本命令
    :param ip_address: 设备IP地址
    :param cmd: 命令字符串（如 'SHOW', 'NEXT'）
    :return: 响应状态
    """
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(
                f"http://{ip_address}/{cmd}",
                headers={'Content-Type': 'text/plain'}
            ) as response:
                return response.status < 400
    except Exception as e:
        logging.error(f"发送命令 {cmd} 失败: {e}")
        return False


def send_command(cmd):
    """
    同步发送基本命令
    :param ip_address: 设备IP地址
    :param cmd: 命令字符串（如 'SHOW', 'NEXT'）
    :return: 响应状态
    """
    try:
        response = requests.post(
            f"http://{ip_address}/{cmd}",
            headers={'Content-Type': 'text/plain'}
        )
        return response.ok
    except Exception as e:
        logging.error(f"发送命令 {cmd} 失败: {e}")
        return False


async def send_next_async():
    """
    异步发送 NEXT 命令
    :param ip_address: 设备IP地址
    :return: 响应状态
    """
    return await send_command_async('NEXT')


def send_next():
    """
    同步发送 NEXT 命令
    :param ip_address: 设备IP地址
    :return: 响应状态
    """
    return send_command('NEXT')


async def send_show_async():
    """
    异步发送 SHOW 命令
    :param ip_address: 设备IP地址
    :return: 响应状态
    """
    return await send_command_async('SHOW')


def send_show():
    """
    同步发送 SHOW 命令
    :param ip_address: 设备IP地址
    :return: 响应状态
    """
    return send_command('SHOW')


async def send_load_async(data):
    """
    异步发送 LOAD 命令和数据
    :param ip_address: 设备IP地址
    :param data: 要发送的数据字符串
    :return: 响应状态
    """
    try:
        # 添加数据长度和LOAD标识
        payload = data + word_to_str(len(data)) + 'LOAD'
        
        async with aiohttp.ClientSession() as session:
            async with session.post(
                f"http://{ip_address}/LOAD",
                headers={'Content-Type': 'text/plain'},
                data=payload
            ) as response:
                return response.status < 400
    except Exception as e:
        logging.error(f"发送LOAD数据失败: {e}")
        return False


def send_load(data):
    """
    同步发送 LOAD 命令和数据
    :param ip_address: 设备IP地址
    :param data: 要发送的数据字符串
    :return: 响应状态
    """
    try:
        # 添加数据长度和LOAD标识
        payload = data + word_to_str(len(data)) + 'LOAD'
        
        response = requests.post(
            f"http://{ip_address}/LOAD",
            headers={'Content-Type': 'text/plain'},
            data=payload
        )
        return response.ok
    except Exception as e:
        logging.error(f"发送LOAD数据失败: {e}")
        return False


async def send_init_async():
    """
    异步发送初始化命令
    :param ip_address: 设备IP地址
    :param epd_ind: 电子墨水屏索引
    :return: 响应状态
    """
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(
                f"http://{ip_address}/EPD",
                headers={'Content-Type': 'text/plain'},
                data=byte_to_str(epd_ind)
            ) as response:
                return response.status < 400
    except Exception as e:
        logging.error(f"发送初始化命令失败: {e}")
        return False


def send_init():
    """
    同步发送初始化命令
    :param ip_address: 设备IP地址
    :param epd_ind: 电子墨水屏索引
    :return: 响应状态
    """
    try:
        response = requests.post(
            f"http://{ip_address}/EPD",
            headers={'Content-Type': 'text/plain'},
            data=byte_to_str(epd_ind)
        )
        return response.ok
    except Exception as e:
        logging.error(f"发送初始化命令失败: {e}")
        return False


async def send_data_async(base64_str):
    """
    异步发送数据到电子墨水屏
    :param base64_str: base64格式的图片字符串
    :return: 响应状态
    """
    # init -> load(n) -> show  or init -> load(n) -> next -> load(n) -> show
    a = await base64_to_pixel_array_async(base64_str)

    upload_data = get_upload_data(a)
 
    init = await send_init_async()
    if not init:
        return False
    
    for i in range(len(upload_data)):
        for j in range(len(upload_data[i])):
            load = await send_load_async(upload_data[i][j])
            if not load:
                return False

        if i == 0 and len(upload_data) == 2:
            next_cmd = await send_next_async()
            if not next_cmd:
                return False
 
    show = await send_show_async()
    if not show:
        return False
    return True
def send_data(base64_str):
    """
    同步发送数据到电子墨水屏
    :param ip_address: 设备IP地址
    :param epd_ind: 电子墨水屏索引
    :param width: 图片宽度
    :param height: 图片高度
    :param base64_str: base64格式的图片字符串
    :param use_color_mode: 是否使用彩色模式
    :return: 响应状态
    """
    # init -> load(n) -> show  or init -> load(n) -> next -> load(n) -> show
    a = base64_to_pixel_array(base64_str)

    upload_data = get_upload_data(a)

    print(upload_data)

    init = send_init()
    if not init:
        return False

    for i in range(len(upload_data)):
        for j in range(len(upload_data[i])):
            load = send_load(upload_data[i][j])
            if not load:
                return False

        if i == 0 and len(upload_data) == 2:
            next_cmd = send_next()
            if not next_cmd:
                return False

    show = send_show()
    if not show:
        return False
    return True